package com.edu.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.api.entity.commentdto.CourseCommentDto;
import com.edu.api.entity.common.*;
import com.edu.api.entity.user.User;
import com.edu.user.service.UserService;
import com.edu.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseDTO resetBackstagePwdById(Integer id) {
        User user = new User();
        user.setId(id);
        user.setPassword(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex("ppjy888".getBytes()).getBytes()));
        userMapper.updateById(user);
        return new ResponseDTO<>(Code.UPDATE_OK, "成功", null);
    }

    @Override
    public ResponseDTO register(String phone, String password,String name, String regIp,String portrait) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone).eq("is_del",0).eq("type","0");
        List<User> users = userMapper.selectList(queryWrapper);
        if (!users.isEmpty()) {
            if (!users.get(0).getAccountNonExpired().equals(true)) {
                return new ResponseDTO<>(Code.GET_ERR, "无效用户", null);
            }
            if (!users.get(0).getCredentialsNonExpired().equals(true)) {
                return new ResponseDTO<>(Code.GET_ERR, "账号已过期", null);
            }
            if (!users.get(0).getAccountNonLocked().equals(true)) {
                return new ResponseDTO<>(Code.GET_ERR, "账号锁定", null);
            }
            if ("DISABLE".equals(users.get(0).getStatus())) {
                return new ResponseDTO<>(Code.GET_ERR, "账号被禁用", null);
            }
            if (DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(password.getBytes()).getBytes()).equals(users.get(0).getPassword())){
                return new ResponseDTO<>(Code.GET_OK, "成功", JwtUtil.getJwtToken(users.get(0).getId()+"",users.get(0).getName()));
            }
            return new ResponseDTO<>(Code.GET_ERR, "账号或密码错误", null);
        }
        User user = new User();
        user.setPhone(phone);
        user.setType("0");
        user.setPassword(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(password.getBytes()).getBytes()));
        user.setRegIp(regIp);
        user.setType("0");
        if (name != ""){
            user.setName(name);
            user.setPortrait(portrait);
        }else{
            user.setName("泡泡用户"+System.currentTimeMillis());
        }
        userMapper.register(user);
        return new ResponseDTO<>(Code.GET_OK, "成功", JwtUtil.getJwtToken(user.getId()+"",user.getName()));
    }

    @Override
    public ResponseDTO getUserInfo(HttpServletRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",JwtUtil.getMemberIdByJwtToken(request));
        User user = userMapper.selectOne(queryWrapper);
        return new ResponseDTO<>(Code.GET_OK, "成功", user);

    }

    @Override
    public ResponseDTO updateUser(User user) {
        userMapper.updateById(user);
        return new ResponseDTO<>(Code.GET_OK, "成功", null);
    }

    @Override
    public ResponseDTO updatePassword(String id, String newPwd, String oldPwd) {
        User user = userMapper.selectById(id);
        if (user.getPassword().equals(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(oldPwd.getBytes()).getBytes()))){
            user.setPassword(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(newPwd.getBytes()).getBytes()));
            userMapper.updateById(user);
            return new ResponseDTO<>(Code.GET_OK, "成功", null);
        }
        return new ResponseDTO<>(Code.GET_ERR, "原密码错误", null);
    }

    @Override
    public Integer checkPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone).eq("is_del",0);
        return userMapper.selectOne(queryWrapper) == null ? 0 : 1;
    }

    @Override
    public ResponseDTO backstageLogin(String phone, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone).eq("is_del",0).eq("type","1");
        List<User> users = userMapper.selectList(queryWrapper);
        if (!users.isEmpty()) {
            if (!users.get(0).getAccountNonExpired().equals(true)) {
                return new ResponseDTO<>(Code.GET_ERR, "无效用户", null);
            }
            if (!users.get(0).getCredentialsNonExpired().equals(true)) {
                return new ResponseDTO<>(Code.GET_ERR, "账号已过期", null);
            }
            if (!users.get(0).getAccountNonLocked().equals(true)) {
                return new ResponseDTO<>(Code.GET_ERR, "账号锁定", null);
            }
            if (DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(password.getBytes()).getBytes()).equals(users.get(0).getPassword())){
                return new ResponseDTO<>(Code.GET_OK, "成功", JwtUtil.getJwtToken(users.get(0).getId()+"",users.get(0).getName()));
            }
            return new ResponseDTO<>(Code.GET_ERR, "账号或密码错误", null);
        }
        return new ResponseDTO<>(Code.GET_ERR, "账号或密码错误", null);
    }

    @Override
    public ResponseDTO getAllUser(Pageable pageable,User user) throws ParseException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        Date parse = null;
        Date parse2 = null;
        if (!user.getCreateTime().equals("NaN-NaN-NaN")){
            parse = new SimpleDateFormat("yyyy-MM-dd").parse(user.getCreateTime());
            parse2 = new SimpleDateFormat("yyyy-MM-dd").parse(user.getUpdateTime());
        }
        queryWrapper.eq("is_del",0).like("name",user.getName()).like("phone",user.getPhone())
        .eq(!"".equals(user.getStatus()),"status",user.getStatus()).eq(!"".equals(user.getType()),"type",user.getType())
        .ge(!"NaN-NaN-NaN".equals(user.getCreateTime()),"create_time",parse)
        .le(!"NaN-NaN-NaN".equals(user.getUpdateTime()),"update_time",parse2);
        long total = userMapper.selectCount(queryWrapper);
        long pages = 0;
        if(total>0){
            //计算总页码
            pages = total % pageable.getSize() == 0 ? total / pageable.getSize() : total / pageable.getSize() + 1;
            //页码修正
            pageable.setPage(pageable.getPage() < 1 ? 1 : pageable.getPage());
            pageable.setPage(pageable.getPage() > pages ? pages : pageable.getPage());
            //起始下标
            pageable.setIndex((pageable.getPage() - 1) * pageable.getSize());
        }else{
            pageable.setPage(0);
            pageable.setIndex(0);
        }
        Page<User> userPage = new Page<>(userMapper.getAllUser(pageable,user), pageable.getPage(), total, pages);

        return new ResponseDTO(Code.GET_OK,"成功",userPage);
    }

    @Override
    public ResponseDTO updateUserStatus(Integer id, String status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        userMapper.updateById(user);
        return new ResponseDTO(Code.SAVE_OK,"成功",null);
    }

    @Override
    public ResponseDTO addOrUpdateBackStageUser(User user,HttpServletRequest request) {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper();
            if (user.getId()==null){
                queryWrapper.eq("phone",user.getPhone()).eq("type",1).eq("is_del",0);
                if (userMapper.selectOne(queryWrapper)!=null){
                    return new ResponseDTO(Code.SAVE_ERR,"手机号重复",null);
                }
                user.setStatus("1");
                user.setPassword(DigestUtils.md5DigestAsHex(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()).getBytes()));
                user.setRegIp(request.getRemoteAddr());
                user.setType("1");
                userMapper.register(user);
                return new ResponseDTO(Code.SAVE_OK,"添加成功",null);
            }else {
                queryWrapper.eq("phone",user.getPhone()).eq("type",1).eq("is_del",0).ne("id",user.getId());
                if (userMapper.selectOne(queryWrapper)!=null){
                    return new ResponseDTO(Code.SAVE_ERR,"手机号重复",null);
                }
                 userMapper.updateById(user);
                return new ResponseDTO(Code.SAVE_OK,"修改成功",null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseDTO(Code.SAVE_OK,"操作失败",null);
        }
    }

    @Override
    public ResponseDTO deleteUserByIds(List ids) {
        userMapper.deleteUserByIds(ids);
        return new ResponseDTO(Code.DELETE_OK,"成功",null);
    }


}




